<?php 
/**
*	短信接口
*/
class smsChajian extends Chajian{
	
	public function send($tomobile,$tplnum, $params=array(),$provider='',$addlog=true)
	{
		if(isempt($tomobile))return returnerror('接收人手机号不能为空');
		if($provider=='')$provider = getconfig('sms_provider');
		if(isempt($provider))$provider = 'smsrock';

		$qiannum  = getconfig('sms_sign');
		if(isempt($qiannum) && $provider=='smsrock')$qiannum='rockreim';
		if(isempt($qiannum))return returnerror('未配置签名');
		
		if($tplnum=='yzm'){
			$tpls = getconfig('sms_codetpl');
			if(isempt($tpls))$tpls = 'defyzm';
			$tplnum = $tpls;
		}
		$obj 	  = c(''.$provider.'');
		if(!method_exists($obj, 'send'))return returnerror('没有开发'.$provider.'的短信接口');
		
		//return returnsuccess('ok');
		
		$barr 	  = $obj->send($tomobile,$qiannum, $tplnum, $params);
		if(!$barr['success'] && $addlog)m('log')->adderror('短信', $barr['msg']);//记录日志
		
		return $barr;
	}
	
	
	/**
	*	获取验证码(1分钟内只能获取一次)，有效期5分钟
	*	$tomobile 接收手机号
	*	$qiannum 签名编号
	*	$tplnum 模版编号
	*	方法:$barr = c('sms')->getcode($mobile,$gtype, $device);
	*/
	public function getcode($mobile,$gtype, $device)
	{
		$time   = 60; //这时间内只能一次
		$cache 	= c('cache');
		$key 	= $cache->get('mo'.$mobile.'');
		if(!isempt($key)){
			$mshu = time()-$key;
			$jg   = $time-$mshu;
			if($jg>0)return returnerror('获取太频繁了，请'.$jg.'秒后在试');
		}
		
		$key 	= $cache->get('mo'.$device.'');
		if(!isempt($key)){
			$mshu = time()-$key;
			$jg   = $time-$mshu;
			if($jg>0)return returnerror('获取太频繁了，请'.$jg.'秒后在试');
		}
		
		$code 	= rand(100000,999999);
		$params['code'] = $code;
		
		
		if(getconfig('systype')=='dev'){
			m('log')->add('短信验证码',''.$mobile.'的验证码是'.$code.'，来源'.$gtype.'');
			$barr = returnsuccess('ok');
		}else{
			$barr =  $this->send($mobile,'yzm', $params);
		}
		
		if($barr['success']){
			$cache->set('mo'.$mobile.'', time(), 60);
			$cache->set('mo'.$device.'', time(), 60);
			
			//记录起来
			$key = md5($mobile.$gtype.$device);
			$cache->set($key, md5('abc'.$code.''), 5*60);//5分钟内容
		}
		
		return $barr;
	}
	
	/**
	*	验证验证码是否正确
	*	bool c('sms')->checkcode($mobile, $code, $gtype, $device);
	*/
	public function checkcode($mobile, $code, $gtype, $device)
	{
		$key = md5($mobile.$gtype.$device);
		$cache 	= c('cache');
		$val = $cache->get($key);
		if($val!=md5('abc'.$code.'')){
			return false;
		}else{
			$cache->del($key);
			return true;
		}
	}
}                               